<?php

/**
 * This is the model class for table "order".
 *
 * The followings are the available columns in table 'order':
 * @property integer $id
 * @property integer $type
 * @property integer $state
 * @property integer $genre
 * @property string $picture
 * @property string $first_name
 * @property string $last_name
 * @property string $address
 * @property string $email
 * @property string $phone
 * @property string $description
 * @property string $create_time
 * @property string $update_time
 * 
 * @property-read $types
 * @property-read $genres
 * @property-read $states
 */
class Order extends EActiveRecord {
    const TYPE_PASTEL = 1;
    const TYPE_GRPHICS = 2;

    const STATE_NEW = 0;
    const STATE_CONFIRMED = 1;
    const STATE_IN_PROCESSING = 2;
    const STATE_FINISHED = 3;

    const GENRE_CARICATURE = 1;
    const GENRE_PORTRAIT = 2;

    public function getGenres() {
        return array(
            self::GENRE_CARICATURE => 'Карикатура',
            self::GENRE_PORTRAIT => 'Портрет',
        );
    }

    public function getTypes() {
        return array(
            self::TYPE_PASTEL => 'Пастел',
            self::TYPE_GRPHICS => 'Графика',
        );
    }

    public function getStates() {
        return array(
            self::STATE_NEW => 'Нова',
            self::STATE_CONFIRMED => 'Потвърдена',
            self::STATE_IN_PROCESSING => 'В обработка',
            self::STATE_FINISHED => 'Завършена',
        );
    }

    public function behaviors() {
        return array(
            'CTimestampBehavior' => array(
                'class' => 'zii.behaviors.CTimestampBehavior',
                'setUpdateOnCreate' => true,
            ),
            'currentStatus' => array(
                'class' => 'AStateMachine',
                'defaultStateName' => self::STATE_NEW,
                'statename' => $this->state,
                'states' => array(
                    array(
                        'class' => 'OrderStateNew',
                        'name' => self::STATE_NEW,
                    ),
                    array(
                        'class' => 'OrderStateConfirmed',
                        'name' => self::STATE_CONFIRMED,
                    ),
                    array(
                        'class' => 'OrderStateProcessing',
                        'name' => self::STATE_IN_PROCESSING,
                    ),
                    array(
                        'class' => 'OrderStateFinihed',
                        'name' => self::STATE_FINISHED,
                    ),
                ),
            ),
        );
    }

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Order the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'order';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('type, picture, email, phone, genre', 'required'),
            array('type, genre', 'numerical', 'integerOnly' => true),
            array('email', 'email'),
            array('first_name, last_name, address, email, phone, description', 'length', 'max' => 255),
            array('picture', 'file',
                'types' => 'jpg, gif, png',
                'wrongType' => 'Моля качвайте само снимки от тип: {extensions}!',
                'maxSize' => 4194304 /* 4 MB in bytes */,
                'tooLarge' => 'Файлът е прекалено голям!',),
            array('state, create_time, update_time', 'safe'),
            array('id, type, genre, state, first_name, last_name, address, email, phone', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'type' => 'Тип',
            'genre' => 'Жанр',
            'state' => 'Състояние',
            'picture' => 'Снимка',
            'first_name' => 'Име',
            'last_name' => 'Фамилия',
            'address' => 'Адрес',
            'email' => 'Email',
            'phone' => 'Телефон',
            'description' => 'Описание',
            'create_time' => 'Подадена на',
            'create_time' => 'Последна промяна',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('type', $this->type);
        $criteria->compare('genre', $this->genre);
        $criteria->compare('state', $this->state);
        
        $criteria->compare('first_name', $this->first_name, true);
        $criteria->compare('last_name', $this->last_name, true);
        $criteria->compare('address', $this->address, true);
        $criteria->compare('email', $this->email, true);
        $criteria->compare('phone', $this->phone, true);

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
        ));
    }

    private static $uploadsFilePath;

    /**
     * Genereates the file path, where to store the 
     * 
     * @param type $name
     * @return string Returns the filesystem path to the 
     */
    public function getPicturePath($name = null) {
        if ($name === null)
            $name = $this->picture;

        if (self::$uploadsFilePath === null)
            self::$uploadsFilePath = Yii::getPathOfAlias('webroot')
                    . DIRECTORY_SEPARATOR
                    . Yii::app()->params['uploadsDirectoryName']
                    . DIRECTORY_SEPARATOR
                    . Yii::app()->params['orderFilesDirectoryName']
                    . DIRECTORY_SEPARATOR;

        return self::$uploadsFilePath . $name;
    }

    private static $picturesUrl;

    public function getPictureUrl($absolute=false, $name=null) {
        if ($name === null)
            $name = $this->picture;

        if (self::$picturesUrl === null)
            self::$picturesUrl = Yii::app()->getBaseUrl($absolute)
                    . '/'
                    . Yii::app()->params['uploadsDirectoryName']
                    . '/'
                    . Yii::app()->params['orderFilesDirectoryName']
                    . '/';

        return self::$picturesUrl . $name;
    }

    // Manage file uploads inside the model.
    protected function beforeValidate() {
        if ($this->getScenario() == 'insert')
            $this->picture = CUploadedFile::getInstance($this, 'picture');

        return parent::beforeValidate();
    }

    protected function afterSave() {
        if ($this->getScenario() == 'insert')
            $this->picture->saveAs($this->getPicturePath($this->picture->name));

        parent::afterSave();
    }

    protected function afterDelete() {
        // Delete picture file.
        @unlink($this->getPicturePath());

        parent::afterDelete();
    }

    public function getFullName() {
        return "$this->first_name $this->last_name";
    }

}